<style lang="less">
  .ue-stowagecore {
    .el-row {
      margin-bottom: 20px;
    }

    .el-col {
      border-radius: 4px;
    }

    .bg-purple-dark {
      background: #ffffff;
    }

    .grid-content {
      border-radius: 4px;
      min-height: 36px;
    }

    .el-form-item {
      margin: 0px 20px 15px 20px;
    }

    .f-bs1 {
      border: 1px solid #dfe6ec;
    }

    .el-collapse {
      border: 0px;
      .el-collapse-item {
        border: 1px solid #dfe6ec;
        margin-bottom: 10px;
        .el-collapse-item__header {
          font-weight: bold;
          .el-collapse-item__header__arrow {
            display: none;
          }
        }
        .el-collapse-item__content {
          padding-bottom: 0px;
        }
        .el-collapse-item__wrap {
          border-bottom: 0px;
        }
      }
    }

    .el-form-item[data-v-7da61f17] {
      margin: 0 0 0 0
    }

    .f-mt10 {
      margin-top: 10px;
    }

    .f-ml20 {
      margin-left: 20px;
    }

    .f-mr20 {
      margin-right: 20px;
    }

    .f-mb10 {
      margin-bottom: 10px;
    }

    .f-tar {
      text-align: right;
    }

    .f-h30 {
      height: 30px;
    }

    .f-c-red {
      color: red;
    }

    .el-radio-group {
      width: 60%;
    }

    .el-radio-invoice {
      margin-right: 30px;
    }

    .f-color {
      color: #25baaf;
    }

    .el-textarea {
      width: 86%;
    }

    .f-mb {
      margin-bottom: 0;
    }

    .f-fr {
      float: right;
    }

    .f-fl {
      float: left;
    }

    .f-lh38 {
      line-height: 38px;
    }

    .el-select {
      width: 100%;
    }

    .f-w233 {
      width: 100%;
    }

    .el-form-item__label {
      width: 150px;
    }

    .el-date-editor.el-input {
      width: 100%;
    }

    li {
      list-style-type: none;
    }

    .color-c8c8c8 {
      color: #c8c8c8;
    }

    .f-mt {
      margin-top: 0;
    }

    .width70 {
      width: 70%;
    }

    .el-transfer-panel {
      width: 300px;
    }
  }
  .dialog-form-label{
    label{
      width: 120px;
    }

  }
  .dialog-form-content{
    width: 350px
  }
</style>
<template>
  <section class="ue-stowagecore">

    <!--工具条-->
    <search-bar more-display>
      <el-row>
        <el-col :span="8">
          <el-form-item label="节点名称">
            <el-input v-model="searchCondition.LIKE_name"
                      placeholder="请输入节点名称"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </search-bar>
    <!-- 操作 -->
    <el-col :span="24" style="margin-bottom: 10px">
      <el-button type="primary" @click="handleAdd">新增</el-button>
      <el-button type="primary" @click="myReset" style="float: right">重置</el-button>
      <el-button type="primary" @click="searchStowageCore" style="float: right">查询</el-button>
    </el-col>
    <!--列表-->
    <el-table :data="tableData" highlight-current-row border @sort-change="sortChange"
              @selection-change="selsChange" v-loading="listLoading" style="width: 100%;">
      <el-table-column type="index" label="序号" width="100" >
      </el-table-column>
      <el-table-column prop="name" label="名称" >
      </el-table-column>
      <el-table-column prop="addressName" label="地址" width="500" >
      </el-table-column>
      <el-table-column prop="" label="辐射城市管理" width="380"  >
        <template slot-scope="scope">
          <el-button  type="primary" @click="radiateCityBYId(scope.$index, scope.row)">管理
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250">
        <template slot-scope="scope">
          <el-button  type="primary" @click="getEditBYId(scope.$index, scope.row)">编辑 </el-button>
          <el-button type="danger"  @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-pagination
        :current-page="currentPage"
        :page-size="pageSize"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total,sizes,prev, pager, next, jumper"
        :total="total" style="float: right">
      </el-pagination>
    </el-col>
    <!--新增 弹窗 -->
    <el-dialog :title="dialogTitle" size="tiny" :visible.sync="stowageCoreVisible" :close-on-click-modal="false">
      <el-form :model="stowageCore" :rules="rules" label-width="80px" ref="stowageCore">
        <el-form-item label="名称" class="dialog-form-label" prop="name">
          <el-input v-model="stowageCore.name" class="dialog-form-content" placeholder="请输入名称"></el-input>
        </el-form-item>
        <el-form-item label="公司地址" prop="myAddress" class="dialog-form-label">
          <el-cascader class="dialog-form-content" :props="addressProps" :options="addressDictData" change-on-select
                       placeholder="请选择地址"
                       v-model="stowageCore.myAddress">
          </el-cascader>
        </el-form-item>
        <el-form-item label="详细地址" class="dialog-form-label" prop="street">
          <el-input v-model="stowageCore.street" class="dialog-form-content"
                    placeholder="请输入详细地址"></el-input>
        </el-form-item>
        <el-form-item label="隶属机构" prop="currentOrganizationIds" class="dialog-form-label">
          <el-cascader
            class="dialog-form-content"
            placeholder="请选择隶属机构"
            :options="$store.state.initOrganizations"
            :props="{label: 'name',value: 'id'}"
            change-on-select
            v-model="stowageCore.currentOrganizationIds"
          ></el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="stowageCoreVisible = false">取消</el-button>
        <el-button type="primary" @click.native="handleSubmit" :loading="submitLoading1">提交</el-button>
      </div>
    </el-dialog>
    <!--打开辐射 弹窗 -->
    <el-dialog :title="radiateTitle"  :visible.sync="radiateCityVisible" :close-on-click-modal="false">
      <el-col :span="24" style="margin-bottom: 10px">
        <el-button type="primary" @click="raidateAdd">新增</el-button>
      </el-col>
      <el-table :data="radiateCityTableData" highlight-current-row border @sort-change="sortChange1"
                @selection-change="selsChange1" v-loading="listLoading1" style="width: 100%;">
        <el-table-column type="index" label="序号" width="100" >
        </el-table-column>
        <el-table-column label="管辖范围(区/县)" >
          <template slot-scope="scope">
            {{scope.row.province}}   {{scope.row.city}}   {{scope.row.county}}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250">
          <template slot-scope="scope">
            <el-button  type="primary" @click="getEditBYId1(scope.$index, scope.row)">编辑地址
            </el-button>
            <el-button type="danger"  @click="handleDel1(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--工具条-->
      <el-row>
        <el-col :span="24" class="toolbar">
          <el-pagination
            :current-page="currentPage1"
            :page-size="pageSize1"
            @size-change="handleSizeChange1"
            @current-change="handleCurrentChange1"
            layout="total,sizes,prev, pager, next, jumper"
            :total="total1" style="float: right">
          </el-pagination>
        </el-col>
      </el-row>
    </el-dialog>
    <!--新增 辐射城市 弹窗 -->
    <el-dialog :title="radiateDetailTitle" size="tiny" :visible.sync="radiateDetailVisible" :close-on-click-modal="false">
      <el-form :model="radiateCity" :rules="rules1" label-width="80px" ref="radiateCity">
        <el-row class="f-mt10 f-mb10">
          <el-col :span="24">
            <el-form-item label="地址" prop="myAddress1">
              <el-cascader class="f-w233" :props="addressProps" :options="addressDictData" change-on-select
                           placeholder="请选择地址"
                           v-model="radiateCity.myAddress1">
              </el-cascader>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="radiateDetailVisible = false">取消</el-button>
        <el-button type="primary" @click="saveRadiateCity" :loading="submitLoading2">提交地址</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>
import {getOrganizationById} from '../../api/organization/Organization';
import { addressDictsSimpleWithType } from '../../api/system/addressDict';

import {
  searchStowageCore,
  saveStowageCore,
  delStowageCore
} from '../../api/system/stowageCore';

import {
  getByStowageCore,
  saveRadiateCity,
  getRadiateCity,
  delRadiateCity
} from '../../api/system/RadiateCity';

import {objToFilter, resetObjNull, getTreeIdAndNameToMap} from '../../lib/util';

export default {
  data () {
    return {
      currentStowageCoreId: '',
      currentOrganizationIds: [],
      addressDictData: [],
      addressProps: {
        value: 'id',
        label: 'name'
      },
      props1: {
        label: 'name',
        value: 'id',
        children: 'children'
      },
      myAddress1: [],
      stowageCoreCenter: [],
      stowageCoreCenter2: [],

      searchCondition: {
        LIKE_name: null
      },
      sels: [],
      types: [],
      tableData: [],
      total: 0,
      currentPage: 1,
      pageSize: 10,
      sortProp: null,
      sortOrder: 'ascending',
      listLoading: false,

      sels1: [],
      types1: [],
      radiateCityTableData: [],
      total1: 0,
      currentPage1: 1,
      pageSize1: 10,
      sortProp1: null,
      sortOrder1: 'ascending',
      listLoading1: false,
      listLoading2: false,

      stowageCoreVisible: false,
      radiateCityVisible: false,
      radiateDetailVisible: false,
      submitLoading: false,
      submitLoading1: false,
      submitLoading2: false,

      dialogTitle: '新增',
      condition: {
        name: '',
        number: ''
      },

      radiateDetailTitle: '新增',

      radiateTitle: '新增',
      // 表单数据
      stowageCore: {
        'id': null,
        'name': null,
        currentOrganizationIds: [],
        'addressId': null,
        'organizationId': null,
        'provinceId': null,
        'stowageOrganizationId': null,
        'cityId': null,
        'countyId': null,
        'street': null,
        'addressName': null,
        'myAddress': []

      },

      // 表单数据
      radiateCity: {
        'id': null,
        'provinceId': null,
        'cityId': null,
        'stowageId': null,
        'countyId': null,
        'myAddress1': []
      },
      // 验证规则
      rules: {
        name: [
          {required: true, message: '请输入名称', trigger: 'blur'},
          {min: 2, max: 60, message: '长度在2到 60 个字符', trigger: 'blur'}
        ],
        myAddress: [
          {type: 'array', required: true, message: '请选择地址', trigger: 'blur'}
        ],
        street: [
          {required: true, message: '请输入详细地址', trigger: 'blur'}
        ],
        currentOrganizationIds: [
          {type: 'array', required: true, message: '请选择机构', trigger: 'change'}
        ]
      },
      // 验证规则
      rules1: {
        myAddress1: [
          {type: 'array', required: true, message: '请选择地址', trigger: 'change'}
        ]
      }

    };
  },
  methods: {

    // 打开辐射城市窗口
    radiateCityBYId (index, row) {
      this.myAddress1 = [];
      this.currentStowageCoreId = row.id;
      let filters = '';
      this.listLoading1 = true;
      getByStowageCore({
        page: this.currentPage1,
        size: this.pageSize1,
        filters: filters,
        id: row.id,
        sorts: (this.sortProp1 === null ? '' : (this.sortOrder1 === 'ascending' ? '-' : '+') + this.sortProp1)
      }).then((res) => {
        this.radiateCityVisible = true;
        this.radiateCityTableData = res.data.detailModelList;
        this.currentPage1 = res.data.currPage;
        this.total1 = res.data.totalCount;
        this.pageSize1 = res.data.pageSize;
        this.listLoading1 = false;
      });
    },

    // 搜索 栏重置
    myReset () {
      resetObjNull(this.searchCondition);
      this.createsDaterange = [];
    },
    loadingLists (filter) {
      this.listLoading = true;
      searchStowageCore({
        filters: filter,
        sort: 'createdDate,desc',
        page: this.currentPage - 1,
        size: this.pageSize
      }).then(res => {
        if (res.status === 200) {
          this.tableData = res.data;
          this.total = Number(res.headers['x-total-count']);
          this.listLoading = false;
        }
      });
    },

    // 搜索
    searchStowageCore () {
      this.loadingLists(objToFilter(this.searchCondition));
    },

    // 删除单条数据操作
    handleDel (index, row) {
      this.$confirm('确认删除该配载节点吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        delStowageCore(row.id).then((res) => {
          this.listLoading = false;
          this.currentPage = 1;
          this.searchStowageCore();
          this.$message({
            message: '删除成功！',
            type: 'success'
          });
        });
      }).catch(() => {
      });
    },

    // 辐射城市删除单条数据操作
    handleDel1 (index, row) {
      this.$confirm('确认删除该辐射城市吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading1 = true;
        delRadiateCity(row.id).then((res) => {
          this.listLoading1 = false;
          this.$message({
            message: '删除成功！',
            type: 'success'
          });
          this.getRadiateCityList();
        });
      }).catch(() => {
      });
    },

    // 打开配载节点编辑界面
    getEditBYId (index, row) {
      this.resetForm();
      this.stowageCore = Object.assign({}, row);
      this.stowageCore.myAddress = [this.stowageCore.provinceId, this.stowageCore.cityId, this.stowageCore.countyId, this.stowageCore.townId];
      if (this.stowageCore.stowageOrganizationId) {
        this.stowageCore.currentOrganizationIds = this.stowageCore.stowageOrganizationId.split(',');
      }
      this.EditTitle = '修改';
      this.stowageCoreVisible = true;
    },

    // 打开辐射城市编辑界面
    getEditBYId1 (index, row) {
      getRadiateCity(row.id).then((res) => {
        if (res.data.successFlg) {
          this.radiateCity = res.data.obj;
          this.radiateCity.myAddress1 = [res.data.obj.provinceId, res.data.obj.cityId, res.data.obj.countyId];
        }
      });
      this.currentOrganizationIds = Object.assign([], this.currentOrganizationIds);
      this.radiateDetailTitle = '修改';
      this.radiateDetailVisible = true;
    },

    addressValue (value) {
      if (value) {
        return value;
      } else {
        return null;
      }
    },
    // 新增数据提交
    handleSubmit () {
      this.$refs['stowageCore'].validate((valid) => {
        if (valid) {
          // 表单验证
          this.stowageCore.stowageOrganizationId = this.stowageCore.currentOrganizationIds.join(',');
          if (this.stowageCore.myAddress[2] == null) {
            return this.$message.error('请选择到区/县一级地址');
          }
          let addressIds = [this.addressValue(this.stowageCore.myAddress[0]), this.addressValue(this.stowageCore.myAddress[1]), this.addressValue(this.stowageCore.myAddress[2])];
          let addressObject = getTreeIdAndNameToMap(addressIds, this.addressDictData);
          this.stowageCore.provinceId = addressIds[0];
          this.stowageCore.cityId = addressIds[1];
          this.stowageCore.countyId = addressIds[2];
          this.stowageCore.addressName = addressObject.get(addressIds[0]) + addressObject.get(addressIds[1]) + addressObject.get(addressIds[2]) + this.stowageCore.street;
          this.submitLoading = true;
          saveStowageCore(this.stowageCore).then((res) => {
            this.submitLoading = false;
            if (res.status === 201) {
              this.stowageCoreVisible = false;
              this.searchStowageCore();
              this.$message.success('保存/修改成功！');
            } else {
              this.$message.error(res.data.errorMsg);
            }
          }).catch(function (error) {
            console.log(error);
          });
        } else {
          return false;
        }
      });
    },

    // 新增辐射城市数据提交
    saveRadiateCity () {
      // 表单验证
      this.$refs['radiateCity'].validate((valid) => {
        if (valid) {
          if (this.radiateCity.myAddress1.length === 1) {
            return this.$message.error('请最少选择到城市');
          }
          let addressIds = [this.radiateCity.myAddress1[0], this.radiateCity.myAddress1[1], this.radiateCity.myAddress1[2]];
          let addressObject = getTreeIdAndNameToMap(addressIds, this.addressDictData);
          if (this.radiateCity.myAddress1.length === 2) {
            this.radiateCity.provinceId = addressIds[0];
            this.radiateCity.province = addressObject.get(addressIds[0]);
            this.radiateCity.cityId = addressIds[1];
            this.radiateCity.city = addressObject.get(addressIds[1]);
          }
          if (this.radiateCity.myAddress1.length === 3) {
            this.radiateCity.provinceId = addressIds[0];
            this.radiateCity.province = addressObject.get(addressIds[0]);
            this.radiateCity.cityId = addressIds[1];
            this.radiateCity.city = addressObject.get(addressIds[1]);
            this.radiateCity.countyId = addressIds[2];
            this.radiateCity.county = addressObject.get(addressIds[2]);
          }
          this.radiateCity.stowageId = this.currentStowageCoreId;
          this.submitLoading2 = true;
          saveRadiateCity(this.radiateCity).then((res) => {
            this.submitLoading2 = false;
            if (res.status === 201) {
              this.$message.success('保存/修改成功！');
              this.radiateDetailVisible = false;
              this.getRadiateCityList();
            } else {
              this.$message.error(res.data.errorMsg);
            }
          }).catch(function (error) {
            console.log(error);
          });
        } else {
          return false;
        }
      });
    },

    // 弹出添加窗体
    handleAdd () {
      this.currentOrganizationIds = [];
      this.stowageCore.myAddress = [];
      this.dialogTitle = '新增';
      this.resetForm();
      this.stowageCoreVisible = true;
    },

    // 打开辐射城市的新增窗口
    raidateAdd () {
      this.resetForm1();
      this.radiateCity.myAddress1 = [];
      this.radiateDetailTitle = '新增';
      this.radiateDetailVisible = true;
    },

    // 重置表单
    resetForm () {
      if (this.$refs.stowageCore) {
        this.$refs.stowageCore.resetFields();
      }
      // 当先点击修改，再点击新增，会出现值没有清空,修复处理
      for (let p in this.stowageCore) {
        if (this.stowageCore[p] instanceof Array) {
          this.stowageCore[p] = [];
        } else {
          this.stowageCore[p] = null;
        }
      }
    },
    resetForm1 () {
      if (this.$refs.radiateCity) {
        this.$refs.radiateCity.resetFields();
      }
      // 当先点击修改，再点击新增，会出现值没有清空,修复处理
      for (let p in this.radiateCity) {
        if (this.radiateCity[p] instanceof Array) {
          this.radiateCity[p] = [];
        } else {
          this.radiateCity[p] = null;
        }
      }
    },

    // 多选操作
    selsChange (sels) {
      this.sels = sels;
    },
    // 排序操作
    sortChange (o) {
      this.sortProp = o.prop;
      this.sortOrder = o.order;
      this.searchStowageCore();
    },
    // 每页几条操作
    handleSizeChange (val) {
      this.pageSize = val;
      this.searchStowageCore();
    },
    // 第几页操作
    handleCurrentChange (val) {
      this.currentPage = val;
      this.searchStowageCore();
    },

    //            辐射
    // 多选操作
    selsChange1 (sels) {
      this.sels1 = sels;
    },
    // 排序操作
    sortChange1 (o) {
      this.sortProp1 = o.prop;
      this.sortOrder1 = o.order;
      this.getRadiateCityList();
    },
    // 每页几条操作
    handleSizeChange1 (val) {
      this.pageSize1 = val;
      this.getRadiateCityList();
    },
    // 第几页操作
    handleCurrentChange1 (val) {
      this.currentPage1 = val;
      this.getRadiateCityList();
    },

    // 获取辐射城市列表

    getRadiateCityList () {
      let filters = '';
      getByStowageCore({
        page: this.currentPage1,
        size: this.pageSize1,
        filters: filters,
        id: this.currentStowageCoreId,
        sorts: (this.sortProp1 === null ? '' : (this.sortOrder1 === 'ascending' ? '-' : '+') + this.sortProp1)
      }).then((res) => {
        this.radiateCityVisible = true;
        this.radiateCityTableData = res.data.detailModelList;
        this.currentPage1 = res.data.currPage;
        this.total1 = res.data.totalCount;
        this.pageSize1 = res.data.pageSize;
        this.listLoading1 = false;
      });
    },
    // 地址数据删除为空的子地址
    clearEmptyChildren (items) {
      let o = this.clearEmptyChildren;
      items.forEach(function (v) {
        if (v.children.length === 0) {
          delete v.children;
        } else {
          o(v.children);
        }
      });
    }
  },
  mounted () {
    getOrganizationById(this.$store.state.currentOrganizationId).then(res => {
      if (res.data.successFlg) {
        if (res.data.obj) {
          let ids = Object.assign([], res.data.obj.pids);
          ids.push(res.data.obj.id);
          this.currentOrganizationIds = Object.assign([], ids);
        } else {
          this.currentOrganizationIds = [];
        }
      }
    });
    addressDictsSimpleWithType('level=1,2,3').then(res => {
      let list = res.data.detailModelList;
      this.addressDictData = list;
      this.clearEmptyChildren(list);
    }).catch(err => {
      console.error(err);
    });
    this.$store.commit('initOrganizations');
    this.searchStowageCore();
    this.$store.commit('initDict');
  }
};
</script>
